<?php
/**
 * Created by PhpStorm.
 * User: shutao
 * Date: 2018/9/22
 * Time: 10:53
 */

namespace wechat\controllers;

use tt\common\components\TtPagination;
use tt\common\help\ModelHelper;
use tt\common\help\RequestHelp;
use tt\common\help\ResponseHelp;
use ttcommon\aop\annotation\ControllerAnnotation;
use ttcommon\base\Arrays;
use ttcommon\base\Data;
use ttext\backend\admin\hook\QuickMenuHook;
use wechat\models\WeContent;
use yii\base\UserException;

/**
 * @title [微信]内容回复模板
 */
class ContentController extends BaseWechatController implements ControllerAnnotation
{
    /**
     * @title 列表
     * @return string
     */
    public function actionIndex()
    {
        if ($api = $this->hasApi()) {
            $query = WeContent::find()->select(['id', 'title', 'type', 'keyword']);
            $pagination = new TtPagination(['totalCount' => $query->count()]);
            $data = [];
            foreach ($query->offset($pagination->offset)->limit($pagination->limit)->asArray()->each() as $item) {
                $item['type_text'] = WeContent::typeText($item['type']);
                $data[] = $item;
            }
            $result = [
                'total' => $pagination->totalCount,
                'result' => $data
            ];
            ResponseHelp::send($result);
        }
        return $this->render('index');
    }

    private function findById($id)
    {
        if (!$model = WeContent::findOne(['id' => $id])) {
            throw new \Exception('找不到指定的数据');
        }
        return $model;
    }

    /**
     * @title 添加/编辑
     * @throws
     * @return string
     */
    public function actionEdit($id = 0)
    {
        QuickMenuHook::$disabled = true;
        $model = $id ? $this->findById($id) : new WeContent();
        if (RequestHelp::isPost()) {
            $data = RequestHelp::requestData();
            if ($postId = Data::hasInt($data, 'id')) {
                if ($postId != $id) {
                    throw new \Exception('参数错误');
                }
            }
            $keys = $model->scenarios()[$model::SCENARIO_DEFAULT];
            Data::hasSet($data, $keys);
            // 如果要追加其它的键，请使用 array_merge($keys,[other])
            $model->attributes = Arrays::values($data, $keys);
            if ($model->validate() && $model->save()) {
                $item = [
                    'id' => $model->id,
                    'title' => $model->title,
                    'type' => $model->type,
                    'keyword' => $model->keyword,
                    'type_text' => WeContent::typeText($model->type)
                ];
                ResponseHelp::send($item);
            } else {
                throw new UserException(ModelHelper::errorMessages($model));
            }
        }
        return $this->render('edit', [
            'model' => $model
        ]);
    }

    /**
     * @title 删除
     * @throws
     */
    public function actionDelete($id)
    {
        if (RequestHelp::isPost()) {
            $model = $this->findById($id);
            if ($model->delete() === false) {
                throw new UserException('删除失败');
            }
            ResponseHelp::send('删除成功');
        } else {
            RequestHelp::throwRequestMethodError();
        }
    }
}